/**
 * Created by wang on 17-6-13.
 */
var rd = require('rd');
var Promise = require('bluebird');
var json2csv = require('json2csv');
var fs = require('fs');

var DATA = {};
var APKNAME = [];
var HOSTARR = [];
var CARS = [];
var HOSTSFILE = [];

getHostFile();
function getHostFile() {
    rd.eachFileFilterSync('host', /\.txt$/, function (f, s) {
        HOSTSFILE.push(f)
    });
    openHostFile(filterEquallyHost);
    openHostFile(getApkName)
}

function openHostFile(cb) {
    for (var i = 0; i < HOSTSFILE.length; i++) {
        var data = fs.readFileSync(HOSTSFILE[i]).toString();
        var hostArr = data.split(/[\n\r]/);
        cb(hostArr, i)
    }
}

function filterEquallyHost(hostArr) {
    for (var j = 0; j < hostArr.length; j++) {
        if (hostArr[j] != "") {
            var host = hostArr[j].substring(6);
            if (hostArr[j].substring(0, 6) == "Host: " && HOSTARR.indexOf(host) == -1) {
                HOSTARR.push(host)
            }
        }
    }
}
function getApkName(hostArr, num) {
    var url = HOSTSFILE[num].split("/");
    var hostName = url[url.length - 1];
    var apkName = hostName.substring(0, hostName.length - 4);


    APKNAME.push(apkName);
    DATA[apkName] = getApkHost(hostArr);
    if (num == HOSTSFILE.length - 1) {
        csvFormat();
    }
}

function getApkHost(hostArr) {
    var hosts = [];
    for (var j = 0; j < hostArr.length; j++) {
        if (hostArr[j] != "" && hostArr[j].substring(0, 6) == "Host: ") {
            var host = hostArr[j].substring(6);
            for (var i = 0; i < HOSTARR.length; i++) {
                if (host == HOSTARR[i]) {
                    hosts.push(host)
                }
            }
        }
    }
    return hosts
}

function csvFormat() {
    for (var j = 0; j < HOSTARR.length; j++) {
        var data = {};
        data.apkName = HOSTARR[j];
        for (var i = 0; i < APKNAME.length; i++) {
            data[APKNAME[i]] = DATA[APKNAME[i]].indexOf(HOSTARR[j]) != -1 ? 1 : 0;
        }
        CARS.push(data)
    }
    APKNAME.unshift("apkName");
    createCsvFile()
}


function createCsvFile() {
    var csv = json2csv({data: CARS, fields: APKNAME});
    fs.writeFile('file.csv', csv, function (err) {
        if (err) throw err;
        console.log('file saved');
    });
}